﻿// ┌────────────────────────────────────────────────
// │  filter class :: requirement                          
// │  1 :: rms.control.js
// │  2 :: rms.dialog.js
// │  3 :: 
// │  4 :: 
// │  5 ::
// └────────────────────────────────────────────────
//=====================================================================================================
//
//=====================================================================================================
if (typeof RMS == 'undefined') RMS = {};
/*
Filter Constructor Class
@param:  {object} properties create control
@return: {object} control class
*/
RMS.CFilter = function (settings) {
    this.filterView = null;
    this.isFirst = true;
    this.dialog = null;

    this.settings = {
        container: '',
        filterId: '0',
        type: '0',
        toolbar: {
            exit: {
                icon: 'exit',
                name: 'Exit',
                click: function () {
                    console.log('exit here');
                }
            }
        }
    };
    $.extend(true, this.settings, settings);

    this.init = function () {
        switch (this.settings.type) {
            case '1':   //inner

                break;

            default:    //dialog

                break;
        }
    };

    this.initAuto = function () {

    };

    this.loadTemplate = function (url, callback) {
        url = url || '../../Mods/_core.filter/filter.htm #ui-dialog-filter';
        $(this.settings.container).load(url, function (text, status, request) {
            if (status == 'success') {
                //process

                //after process, complete
                if (callback) {
                    callback();
                }
            }
        });
    };

    this.loadFilterDialog = function () {
        if (self.Dialog) {
            //if ($.isFunction(self.Dialog.Close)) {
            if ($.isFunction(self.Dialog.Open)) {
                self.Dialog.Open();
            }
            else if (self.Dialog._dialog) {
                self.Dialog._dialog.dialog("open");
            }
        }
        else {
            var width = 500;
            var left = ($(window).width() - width) / 2,
                height = 500;

            if (self.Options.Height != null) {
                height = self.Options.Height;
            }
            else {
                height = $(window).height() - 70;
                if (height <= 0) {
                    height = 500;
                }
            }
            var buttons = [{
                text: 'Display',
                click: function () {
                    var $this = $(this);
                    var options = {
                        Dialog: self.Dialog,
                        FilterData: function (data) {
                            self.Options.FilterClick(data);
                        }
                    };
                    try {
                        self.FilterView.FilterData(options);
                    }
                    catch (e) { console.log('::filter-click: function not found'); }
                },
                id: self.btnFilter
            },
            {
                text: 'Exit',
                click: function () {
                    $(this).dialog("close");
                },
                id: self.btnExit
            }];
            self.Dialog = new CDialog({
                title: 'Filter',
                width: width,
                height: height,
                closeOnEscape: false,
                autoOpen: self.Options.AutoOpen,
                modal: true,
                draggable: true,
                buttonFocus: 0,
                paddingContent: "5px",
                position: [left, self.Options.Top],
                buttons: buttons,
                refresh: {
                    fn: function () {
                        //ObjBase.WindowHTML.iMarkets.Mods.Core.ViewFilter.Refresh();
                    }
                },
                open: function (event, ui, frame) {
                    console.log("Dialog.Open");
                },
                create: function (event, ui) {
                    $('#' + self.btnFilter).addClass('ui-state-disabled').attr({ 'disabled': 'disabled' });
                    self.FilterView = new CFilterView();
                    self.FilterView.init({
                        ContentFilterID: '#content-filter-' + self.Options.FilterID,
                        ViewControlID: '#ddlFilterView-' + self.Options.FilterID,
                        FilterID: self.Options.FilterID,
                        FilterCode: self.Options.FilterCode,
                        callback: function (option) {
                            if (option.height)
                                self.resize(option.height);
                            $('#' + self.btnFilter).removeClass('ui-state-disabled').removeAttr('disabled');
                        }
                    });
                }
            });
            $(self.ContentID).load('../../Mods/_core.filter/filter.htm #ui-dialog-filter', function (text, status, request) {
                if (status == 'success') {
                    var newid = '#ui-dialog-filter-' + self.Options.FilterID;
                    $(self.ContentID).find('#ui-dialog-filter').attr('id', newid.replace('#', ''));
                    self.Dialog.Init(newid);
                    $(newid + ' fieldset').attr('id', 'content-filter-' + self.Options.FilterID);
                    var height = self.Dialog._options.height || $(self.ContentID).height();
                    height -= 70 + 40;
                    $(newid + ' fieldset').slimScroll({ width: '100%', height: height });
                    $('#ddlFilterView').removeAttr('id').attr('id', 'ddlFilterView-' + self.Options.FilterID);
                }
            });
        }
    };

    this.loadFilterContent = function () {
        $(self.ContentID).load('../../Mods/_core.filter/filter.htm #ui-dialog-filter', function (text, status, request) {
            if (status == 'success') {
                var newid = '#ui-content-filter-' + self.Options.FilterID;
                $(self.ContentID).find('#ui-dialog-filter').attr('id', newid.replace('#', ''));
                $(newid + ' fieldset').attr('id', 'content-filter-' + self.Options.FilterID);
                var height = $(self.ContentID).height();
                if (height <= 0) height = '100%';
                $(newid + ' fieldset').slimScroll({ width: '100%', height: height });
                $('#ddlFilterView').removeAttr('id').attr('id', 'ddlFilterView-' + self.Options.FilterID);

                self.FilterView = new CFilterView();
                self.FilterView.init({
                    ContentFilterID: '#content-filter-' + self.Options.FilterID,
                    ViewControlID: '#ddlFilterView-' + self.Options.FilterID,
                    FilterID: self.Options.FilterID,
                    FilterCode: self.Options.FilterCode,
                    callback: function (option) {
                        if (option.height)
                            self.resize(option.height);
                    }
                });
            }
        });
    };

    this.resize = function (height) {
        if (height) {

        }
    };

    this.visible = function (flag) {
        if (this.dialog) {
            if (flag) {
                this.dialog.open();
            }
            else {
                this.dialog.close();
            }
        }
    };

    this.getFilterData = function () {
        if (this.filterView && this.filterView.getFilterViewData) {
            return this.filterView.getFilterViewData();
        }
        return;
    };

    this.reset = function () {
        if (this.filterView) {
            this.filterView.reset();
        }
    };

    this.reload = function () {

    };

    this.update = function (settings) {
        $.extend(true, this.settings, settings);
        return this;
    }

    this.destroy = function () {

    };
};
//=====================================================================================================
//Filter view class
//=====================================================================================================
function CFilterView(options) {
    var self = this;
    this.serviceUrl = 'Core/CoreService.asmx/GetContextData';
    this.FilterViewCompleted = false;
    this.FilterViewData = null;
    this.FilterViewControl = null;
    this.FilterViewParaData = null;
    this.ControlID = null;
    this.ControlLineID = null;
    this.FilterViewPara = null;
    this.Callback = function (opts) { };
    this.LastFilterViewParaIndex = 0;
    this.ParentContentID = null;
    this.ParaAttID = null;

    this.init = function (options) {
        if (options) {
            //fn call after load complete
            if ($.isFunction(options.callback))
                self.Callback = options.callback;

            self.ControlID = options.ViewControlID;
            self.ParentContentID = options.ContentFilterID;
            self.ControlLineID = options.ContentFilterID + ' #filter-view-para-line';
            self.ParaAttID = $.string.Format('ctrPara-{0}-', options.FilterID);

            self.load(options);
        }
    };

    this.autorun = function (options) {
        var objInput = { UserID: '', LanguageID: '129' };
        var inputValue = new CXml('InputValue', objInput).getXml();
        var objExt = { Context: "FilterView", FilterID: options.FilterID.toString() };
        inputValue += new CXml('RequestParams', objExt).getXml();
        objExt = { Context: "FilterParams", FilterID: options.FilterID.toString() };
        inputValue += new CXml('RequestParams', objExt).getXml();
        objExt = { Context: "FilterParaData", FilterID: options.FilterID.toString(), ListFunction: "ByView" };
        inputValue += new CXml('RequestParams', objExt).getXml();
        var paraData = { ClientKey: FWS_SERVER_CONFIG.ClientKey, InputValue: $.HtmlEncode(inputValue) };
        $.Ajax({
            url: self.serviceUrl,
            type: 'post',
            data: paraData,
            dataType: 'xml',
            isUseServiceData: 1,
            success: function (data, textStatus, jqXHR) {
                data = $.FindInXml(data);
                data = data.CSV2JSON2();
                if (data) {
                    if (data[1].length > 0) {
                        var xmlObj = {};
                        $.each(data[2], function (index, item) {
                            xmlObj[item.Code] = item.ValueDefault;
                        });
                        xmlObj.ViewID = data[1][0].ID;
                        xmlObj.ViewerID = data[1][0].ViewerID;
                        xmlObj.Function = data[1][0].DataFunction;

                        var obj = {
                            view: {
                                name: data[1][0].Name,
                                id: data[1][0].ViewerID,
                                type: data[1][0].ViewerType,
                                fData: data[1][0].DataFunction,
                                tableImport: data[1][0].TableImport
                            },
                            filterXml: new CXml('RequestParams', xmlObj).getXml(),
                            data: data[1][0]
                        }

                        if ($.isFunction(options.success))
                            options.success(obj);
                    }
                }
            }
        });
    };

    this.auto = function (options) {
        var objInput = { UserID: '', LanguageID: '129' };
        var inputValue = new CXml('InputValue', objInput).getXml();
        var objExt = { Context: "FilterView", FilterID: options.FilterID.toString() };
        inputValue += new CXml('RequestParams', objExt).getXml();
        var paraData = { ClientKey: FWS_SERVER_CONFIG.ClientKey, InputValue: $.HtmlEncode(inputValue) };
        $.Ajax({
            url: self.serviceUrl,
            type: 'post',
            data: paraData,
            dataType: 'xml',
            isUseServiceData: 1,
            success: function (data, textStatus, jqXHR) {
                data = $.FindInXml(data);
                data = data.CSV2JSON2();
                if (data) {
                    if (data[1].length > 0) {
                        if ($.isFunction(options.success))
                            options.success(data[1][0]);
                    }
                }
            }
        });
    };

    this.load = function (options) {
        var objInput = { UserID: '', LanguageID: '129' };
        var inputValue = new CXml('InputValue', objInput).getXml();
        var objExt = { Context: "FilterView", FilterID: options.FilterID.toString() };
        inputValue += new CXml('RequestParams', objExt).getXml();
        objExt = { Context: "FilterParams", FilterID: options.FilterID.toString() };
        inputValue += new CXml('RequestParams', objExt).getXml();
        objExt = { Context: "FilterParaData", FilterID: options.FilterID.toString(), ListFunction: "ByView" };
        inputValue += new CXml('RequestParams', objExt).getXml();
        var paraData = { ClientKey: FWS_SERVER_CONFIG.ClientKey, InputValue: $.HtmlEncode(inputValue) };
        $.Ajax({
            url: self.serviceUrl,
            type: 'post',
            data: paraData,
            dataType: 'xml',
            isUseServiceData: 1,
            success: function (data, textStatus, jqXHR) {
                data = $.FindInXml(data);
                data = data.CSV2JSON2();
                if (data) {
                    self.FilterViewData = data[1];
                    self.loadHtml(data[1]);
                    self.FilterViewPara = data[2];
                    self.FilterViewParaData = data[3];
                    self.clear();
                    self.loadView();
                    self.loadDetail();
                }
            }
        });
    };
    this.loadHtml = function (data) {
        var html = '', temp = '<option value="{0}">{1}</option>';
        $.each(data, function (index, item) {
            html += $.string.Format(temp, item.ID, item.Name);
        });
        $(self.ControlID).html(html);
        $(self.ControlID).on('change', function () {
            self.loadViewContent($(this).val());
            self.loadDetail();
        });
    };
    this.loadDetail = function () {
        var viewid = $(self.ControlID).val();
        $.each(self.FilterViewData, function (idx, itm) {
            if (itm.ID == viewid) {
                //console.log(itm);
                $(self.ParentContentID).find('.ui-filter-view-detail').val(itm.Description + '\n[V' + itm.ID + ' G' + itm.ViewerID + ']');
                return false;
            };
        });
    };

    this.loadViewContent = function (viewid) {
        self.clear();
        var objInput = { UserID: '', LanguageID: '129' };
        var objExt = { Context: "FilterParams", FilterViewID: viewid.toString() };
        var inputValue = new CXml('InputValue', objInput).getXml();
        inputValue += new CXml('RequestParams', objExt).getXml();
        objExt = { Context: "FilterParaData", FilterViewID: viewid.toString(), ListFunction: "ByView" };
        inputValue += new CXml('RequestParams', objExt).getXml();

        var paraData = { ClientKey: FWS_SERVER_CONFIG.ClientKey, InputValue: $.HtmlEncode(inputValue) };
        $.Ajax({
            url: self.serviceUrl,
            type: 'post',
            data: paraData,
            dataType: 'xml',
            isUseServiceData: 1,
            success: function (data, textStatus, jqXHR) {
                data = $.FindInXml(data);
                data = data.CSV2JSON2();
                if (data) {
                    self.FilterViewPara = data[1];
                    self.FilterViewParaData = data[2];
                    self.loadView();
                }
            }
        });
    };

    this.clear = function () {
        self.FilterViewCompleted = false;
        self.LastFilterViewParaIndex = 0;
        self.FilterViewControl = new Array;
        $(self.ParentContentID + ' div.ui-line-auto-generate').remove();

    };

    this.loadView = function () {
        window.setTimeout(function () {
            self.loadViewPara(self.LastFilterViewParaIndex);
        }, 10);
    };
    this.getFilterViewParaData = function (id) {
        var ret = new Array();
        $.each(self.FilterViewParaData, function (index, item) {
            if (item.FilterParaID == id) {
                ret.push(item);
            }
        });
        return ret;
    };

    this.loadViewPara = function (index) {
        if (index < self.FilterViewPara.length) {
            var filterViewParaData = self.getFilterViewParaData(self.FilterViewPara[index].ID);
            self.createViewPara(self.FilterViewPara[index], filterViewParaData);
        }
        else {
            self.FilterViewCompleted = true;
            //resize, clear,....
            self.Callback({
                height: self.getViewHeight()
            });
        }
    };
    this.createViewPara = function (item, data) {
        var viewpara = new CFilteViewPara();
        viewpara.init({
            ParaAttID: self.ParaAttID,
            item: item,
            data: data,
            container: self.ControlLineID,
            callback: function () {
                window.setTimeout(function () {
                    self.LastFilterViewParaIndex++;
                    self.loadViewPara(self.LastFilterViewParaIndex);
                }, 10);
            }
        });
        self.FilterViewControl.push(viewpara);
    };

    this.getFilterViewPara = function () {
        var ret = {};
        var pattern = '#' + self.ParaAttID;

        var curView = {};
        var curViewid = $(self.ControlID).val();
        $.each(self.FilterViewData, function (idx, itm) {
            if (itm.ID == curViewid) {
                curView = itm;
                return false;
            };
        });

        $.each(self.FilterViewControl, function (index, item) {
            var name = item.Control.ControlId.toString().replace(pattern, '');
            var val = item.get();
            ret[name] = val;
        });

        ret.ViewID = $(self.ControlID).val();
        ret.ViewerID = curView.ViewerID;
        ret.Function = curView.DataFunction;
        ret = new CXml('RequestParams', ret).getXml();
        return ret;
    };

    this.toString = function () {
        return "";
    };

    this.getViewHeight = function () {
        return 500;
    };
    this.getFilterViewData = function () {
        var xml = self.getFilterViewPara(),
            viewData = self.getViewGridID();
        var obj = {
            view: viewData,
            filterXml: xml
        };
        return obj;
    };
    this.getViewGridID = function () {
        var ret = null,
            viewID = $(self.ControlID).val();

        $.each(self.FilterViewData, function (index, item) {
            if (item.ID == viewID) {
                if (item.ViewerID != '') {
                    ret = {
                        name: item.Name,
                        id: item.ViewerID,
                        type: item.ViewerType,
                        fData: item.DataFunction,
                        tableImport: item.TableImport
                    }
                }
                return false;
            }
        });
        return ret;
    };
    this.FilterData = function (options) {
        var data = self.getFilterViewData();
        options.Dialog.Close();
        options.FilterData(data);
    };

    this.reset = function () {
        var _this = this;
        $.each(_this.FilterViewPara, function (idx, it) {
            try {
                var ctrl = _this.FilterViewControl[idx];
                if (ctrl && ctrl.set) {
                    switch (it.Type) {
                        case '5':
                        case '6':
                        case '7':
                            if (it.ValueDefault == '') {
                                ctrl.set(null);
                            }
                            else {
                                ctrl.set(it.ValueDefault);
                            }
                            break;

                        default:
                            ctrl.set(it.ValueDefault);
                            break;
                    }
                }
            } catch (e) {
                console.log('::resetEx', e)
            }
        });
    };
};
//=====================================================================================================
//Filter view parameter class
//=====================================================================================================
RMS.CFilterViewPara = function (settings) {
    this.defaults = {
        data: [],
        container: ''
    };

    $.extend(true, this.defaults, settings);

    this.instance = null;
    this.RowPattern = '<div class="newrow ui-line-auto-generate" {2}><label>{0}</label>{1}</div>';

    this.init = function () {
        this.render();
        //execute after render html complete
        if ($.isFunction(this.defaults.callback)) {
            this.defaults.callback();
        }
    };

    this.render = function () {
        var html = '',
            ctrId = '',
            ctrHtml = '',
            dynamics = '',
            temp = '',
            settings = {},
            callback = function () { },
            width = 300,
            height = 24;

        var item = this.defaults.item;
        //set width control
        switch (item.WidthType) {
            case '1':
                width = 100;
                break;
            case '2':
                width = 200;
                break;
            case '3':
                width = 300;
                break;
            case '-1':
                width = '100%';
                break;
        }
        ctrId = $.string.Format('{0}{1}', this.defaults.ParaAttID, item.Code);
        var disabled = false;
        if (item.IsEnable == 'False') {
            disabled = true;
        }
        settings = { width: width, disabled: disabled, height: height, id: ctrId };

        switch (item.Type) {
            case '1':
                temp = '<input type="text" id="{0}" code="{1}" />';
                break;
            case '2':
                temp = '<input type="text" id="{0}" code="{1}" />';
                break;
            case '3':
                temp = '<input type="text" id="{0}" code="{1}" />';
                break;
            case '5':   //datetime
                temp = '<div id="{0}" class="datetime" code="{1}"></div>';
                if (typeof item.ValueMin != 'undefined' && item.ValueMin != '') {
                    settings.minDate = item.ValueMin;
                }
                if (typeof item.ValueMax != 'undefined' && item.ValueMax != '') {
                    settings.maxDate = obj.ValueMax;
                }
                break;
            case '6':   //datetime
                temp = '<div id="{0}" class="datetime" code="{1}"></div>';
                if (typeof item.ValueMin != 'undefined' && item.ValueMin != '') {
                    settings.minDate = item.ValueMin;
                }
                if (typeof item.ValueMax != 'undefined' && item.ValueMax != '') {
                    settings.maxDate = obj.ValueMax;
                }
                break;
            case '7':   //time
                temp = '<div id="{0}" class="datetime" code="{1}"></div>';
                break;
            case '10':  //combobox
                temp = '<div id="{0}" class="dropdown" code="{1}"></div>';
                settings.source = this.defaults.data;
                break;
            case '20':
                temp = '<div id="{0}" class="dropdown" code="{1}"></div>';
                settings.source = this.defaults.data;
                break;
            case '110': //autocomplete            
                temp = '<input type="text" id="{0}" code="{1}" />';
                settings.items = 1000;
                settings.width -= 2;
                settings.source = function (query, response) {
                    //var objInput = { UserID: '', LanguageID: '129' };
                    //var inputValue = new CXml('InputValue', objInput).getXml();
                    //var objExt = { Context: "FilterParaData", ListFunction: self.Option.item.DataFunction.toString(), Name: query };
                    //inputValue += new CXml('RequestParams', objExt).getXml();
                    //var paraData = { ClientKey: FWS_SERVER_CONFIG.ClientKey, InputValue: $.HtmlEncode(inputValue) };
                    //self.Control.loadData({
                    //    paraData: paraData,
                    //    callback: function (data) {
                    //        if (data[1].length > 0) {
                    //            $.each(data[1], function (index, item) {
                    //                item.label = item.Name;
                    //                item.value = item.Value;
                    //            });
                    //            response(data[1]);
                    //        }
                    //        else {
                    //            response(query);
                    //        }
                    //        $('#' + ctrId + '_popup').addClass('autocomplete-popup');
                    //    }
                    //});
                }
                break;
            case '120':   //tokeninput
                temp = '<input type="text" id="{0}" code="{1}" />';
                settings.width -= 2;
                settings.extraParams = {
                    Context: "FilterParaData",
                    ListFunction: item.DataFunction.toString()
                };
                settings.ClientKey = FWS_SERVER_CONFIG.ClientKey;
                break;
            case '210':  //CAutoCompletes
                temp = '<input type="text" id="{0}" code="{1}" />';
                break;
            case '220':
                temp = '<input type="text" id="{0}" code="{1}" />';
                break;
            default:
                temp = '<input type="text" id="{0}" code="{1}" />';
                break;
        }

        ctrHtml = $.string.Format(temp, ctrId, item.Code);
        var ext = '';
        if (item.IsVisible == 'False') {
            ext = 'style="display:none;"';
        }
        html = $.string.Format(this.RowPattern, item.Name, ctrHtml, ext);
        //add new row in filter
        $(this.defaults.container).after(html);

        //init control        
        var control = new RMS.CControl(settings, callback);
        control.init();

        this.instance = control.getInstance();

        if (typeof item.Css != 'undefined' && item.Css != '') {
            this.instance.$ctrl.addClass(item.Css);
        }

        //set default value
        if (item.ValueDefault) {
            this.setValue(item.ValueDefault);
        }
        else {//null
            this.setValue(null);
        }
    };

    this.getValue = function () {
        if (this.instance) {
            return this.instance.getValue();
        }
        return;
    };
    this.setValue = function (value) {
        if (this.instance) {
            this.instance.setValue(value);
        }
    };
    this.height = function () {
        return 22;
    };
};